package util.parser;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import util.webSearch.Constants;
import util.webSearch.WebResult;
public class ParseBingWebResults implements Constants {

	/**
	 * @param args
	 */
	
public static LinkedList<WebResult> results(String query, String post) {

	LinkedList<WebResult> ret= new LinkedList<WebResult> ();
	
		
		JSONObject obj=(JSONObject) JSONValue.parse(post);
		 Set<Map.Entry<String, JSONObject>> entries = obj.entrySet();
		
		 Iterator<Entry<String, JSONObject>> keys = entries.iterator();
		 
		 if(!obj.containsKey("SearchResponse")) return null;
		 JSONObject response = (JSONObject) obj.get("SearchResponse");
		
		 
		 if(response==null || (response!=null && !response.containsKey("Web"))) return null;
		 
		 JSONObject web = (JSONObject) response.get("Web");
		 
		 
		 if(web==null || (web!=null && !web.containsKey("Results"))) return null;
		 
		 JSONArray results = (JSONArray) web.get("Results");
		 
		 for(int i =0; i  < results.size(); i++){
			 
			 JSONObject result = (JSONObject) results.get(i);
			 
			 String snippet  = (String) result.get("Description");
			 String title = (String) result.get("Title");
			 String url="";
			 try {
				url =  URLDecoder.decode((String) result.get("Url"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			 WebResult n= new WebResult();
			 n.setQuery(query);
			 n.setEngine(Constants.BING);
			 n.setSnippet(snippet);
			 n.setTitle(title);
			 n.setUrl(url);
			 n.setRank(i+1);
	 
			 ret.add(n);
			 
			 
		 }
		 
		return ret;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
